//
//  PhotoEditViewController.m
//  XPhoto
//
//  Created by baboy on 2019/5/29.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "PhotoEditViewController.h"
#import "BKImageView.h"
#import "PHAsset+x.h"
#import "UIButton+x.h"
#import "PhotoAsset+filter.h"
#import "UIImageView+cache.h"
#import "UIImage+x.h"
#import "NSDate+x.h"
#import "BKIndicator.h"
#import "BKOperationQueue.h"
#import "PhotoFilter.h"
#import "SysDict.h"
#import "BKPlayerView.h"
#import "AVVideoComposition+x.h"
#import <AFNetworking/UIImageView+AFNetworking.h>

@interface PhotoEditViewController ()<UIScrollViewDelegate>
@property(nonatomic, strong) NSArray *filters;
@end

@implementation PhotoEditViewController

- (instancetype)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
        
    }
    return self;
}
- (instancetype)initWithPhotos:(NSArray *)photos{
    if (self = [self init]) {
        if (photos) {
            _photos = [NSMutableArray arrayWithArray:photos];
        }
    }
    return self;
}
- (instancetype)initWithAssets:(NSArray *)assets{
    if (self = [self init]) {
        if (assets) {
            _photos = [NSMutableArray array];
            for (NSInteger i = 0, n = assets.count; i < n; i++) {
                PHAsset *asset = [assets objectAtIndex:i];
                PhotoAsset *photoAsset = [[PhotoAsset alloc] initWithAsset:asset];
                if (asset.mediaType == PHAssetMediaTypeImage) {
                    photoAsset.type = PhotoAssetTypePhoto;
                }
                if (asset.mediaType == PHAssetMediaTypeVideo) {
                    photoAsset.type = PhotoAssetTypeVideo;
                }
                [_photos addObject:photoAsset];
            }
        }
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    DLOG(@"%@,contentView:%@", NSStringFromCGRect(self.view.bounds), NSStringFromCGRect(self.contentView.bounds));
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"back", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"done", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
    //    [self performSelector:@selector(toggleNavigationBar) withObject:nil afterDelay:3.0f];
    self.contentView.delegate = self;
    self.pageControl.numberOfPages = self.photos.count;
    self.pageControl.hidden = self.pageControl.numberOfPages <= 1;
    
    self.photoLoadQueue = [[NSOperationQueue alloc] init];
    self.photoLoadQueue.maxConcurrentOperationCount = 1;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupViews];
    [self setupFilters];
    DLOG(@"viewWillAppear:%@,contentView:%@", NSStringFromCGRect(self.view.bounds), NSStringFromCGRect(self.contentView.bounds));
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    DLOG(@"viewDidAppear:%@,contentView:%@", NSStringFromCGRect(self.view.bounds), NSStringFromCGRect(self.contentView.bounds));
    
}

- (void)setupViews{
    if (self.pageViews) {
        [self.pageViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    self.pageViews = [NSMutableArray array];
    CGRect itemFrame = self.contentView.bounds;
    for (int i = 0; i<[self.photos count]; i++) {
        PhotoAsset *photoAsset = [self.photos objectAtIndex:i];
        itemFrame.origin.x = i * itemFrame.size.width;
        
        PhotoPreviewView *itemView = [self createItemViewWithPhotoAsset:photoAsset];
        if ( itemView.mediaType == PhotoAssetTypeVideo ) {
            [itemView.playerView setShouldAutoPlay:YES];
        }
        itemView.frame = itemFrame;
        
        [self.contentView addSubview:itemView];
        [self.pageViews addObject:itemView];
    }
    self.pageControl.numberOfPages = self.photos.count;
    self.contentView.contentSize = CGSizeMake(itemFrame.origin.x+itemFrame.size.width, 0);
}
- (void)setupFilters{
    CGRect buttonFrame = CGRectMake(0, 0, self.bottomPannel.bounds.size.height - 20, self.bottomPannel.bounds.size.height);
    NSArray <SysDictItem*> *items = [SysDict dictForKey:SYS_DICT_PHOTO_FILTER].items;
    
    //原始
    NSMutableArray *filters = [NSMutableArray arrayWithArray:items];
    
    for (NSInteger i = 0, n = filters.count; i<n; i++) {
        SysDictItem *filterItem = [filters objectAtIndex:i];
        buttonFrame.origin.x = i*(buttonFrame.size.width+3);
        UIButton *imageButton = [[UIButton alloc] initWithFrame:CGRectInset(buttonFrame, 2, 2)];
        imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageButton.backgroundColor = [UIColor blueColor];
        imageButton.tag = i;
        [imageButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
        imageButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [imageButton setTitle:filterItem.title forState:UIControlStateNormal];
        imageButton.imageLocation = UIButtonImageLocationTop;
        
        [imageButton addTarget:self action:@selector(selectFilter:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomPannel addSubview:imageButton];
    }
    self.filters = filters;
    self.bottomPannel.contentSize = CGSizeMake(buttonFrame.origin.x + buttonFrame.size.width, 0);
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self layoutImageViewsWithAnimate:NO];
}
- (void)layoutImageViewsWithAnimate:(BOOL)anination{
    [UIView animateWithDuration:anination?0.1f:0 animations:^{
        CGRect imageFrame = self.contentView.bounds;
        for (int i = 0; i<self.pageViews.count; i++) {
            BKImageView *imageView = [self.pageViews objectAtIndex:i];
            imageFrame.origin.x = i * imageFrame.size.width;
            imageView.frame = CGRectInset(imageFrame, 5, 0);
        }
        self.contentView.contentSize = CGSizeMake(self.contentView.bounds.size.width*self.photos.count, 0);
    }];
}

#pragma Buttons
- (void)toggleNavigationBar{
    BOOL flag = !self.navigationController.navigationBar.hidden;
    [self.navigationController setNavigationBarHidden:flag animated:YES];
}
- (void)clickPhoto:(id)imageView{
    [self toggleNavigationBar];
}
- (void)goBack:(id)button{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)applyFilterForCurrentVideo:(NSString *)filterName{
    CIFilter *filter = [PhotoFilter filter:filterName forImage:nil];
    PhotoAsset *photoAsset = [self.photos objectAtIndex:self.pageControl.currentPage];
    photoAsset.filterName = filterName;
    
    PhotoPreviewView *previewView = [self.pageViews objectAtIndex:self.pageControl.currentPage];
    if (previewView.playerView.videoURL) {
        AVAsset *videoAsset = [AVURLAsset URLAssetWithURL:previewView.playerView.videoURL options:nil];
        previewView.playerView.playerItem.videoComposition = [AVVideoComposition videoCompositionWithAsset:videoAsset filter:filter];
        
        UIImage *coverImage = [PhotoFilter image:photoAsset.originImage withFilter:filterName];
        [previewView.playerView setCoverImage:coverImage];
    }
    
    //        CIImage *resultImage = filter.outputImage;
    
    
//    AVVideoComposition *composition = [AVVideoComposition videoCompositionWithAsset:videoAsset applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {
//        NSLog(@"导出中");//针对每一帧的图像做滤镜处理
//        [filter setValue:request.sourceImage forKey:kCIInputImageKey];
//        CIImage *resultImage = filter.outputImage;
//        [request finishWithImage:resultImage context:nil];
//    }];
//    NSString *fn = PHOTO_RANDOM_FILE_NAME(@"mp4");
//    NSString *fp = PHOTO_CACHE_FILE(fn);
//    NSURL *exportURL = [NSURL fileURLWithPath:fp];
//
//
//    AVAssetExportSession *exporter = [[AVAssetExportSession alloc]initWithAsset:videoAsset presetName:AVAssetExportPresetMediumQuality];
//    exporter.videoComposition= composition ;
//    exporter.outputURL = exportURL;
//    exporter.shouldOptimizeForNetworkUse = YES;
//    exporter.outputFileType = AVFileTypeQuickTimeMovie;
//    [exporter exportAsynchronouslyWithCompletionHandler:^{
//        DLOG(@"export status:%ld", exporter.status);
//        switch(exporter.status) {
//            case AVAssetExportSessionStatusFailed:
//                NSLog(@"exporting failed %@",[exporter error]);
//                break;
//            case AVAssetExportSessionStatusCompleted:
//                NSLog(@"导出完成");
//
//                playerView.videoURL = exportURL;
//
//                [PHAsset saveVideoToPhotoLib:exportURL
//                               resultHandler:^(PHAsset * _Nonnull asset, NSError * _Nonnull error) {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [BKIndicator showMessageAndFadeOut:@"保存到相册" completion:nil];
//                    });
//                }];
//                break;
//            case AVAssetExportSessionStatusCancelled:
//                NSLog(@"export cancelled");
//                break;
//            case AVAssetExportSessionStatusUnknown:
//                break;
//            case AVAssetExportSessionStatusWaiting:
//                break;
//            case AVAssetExportSessionStatusExporting:
//                break;
//        }
//    }];
}
- (void)selectFilter:(UIButton*)button{
    DLOG(@"selectFilter:%ld", button.tag);
    //对Image进行处理
    SysDictItem *filterItem = [self.filters objectAtIndex:button.tag];
    PhotoAsset *photoAsset = [self.photos objectAtIndex:self.pageControl.currentPage];
    //处理视频
    if (photoAsset.type == PhotoAssetTypeVideo) {
        [self applyFilterForCurrentVideo:filterItem.key];
        return;
    }
    //处理图片
    if (photoAsset.type == PhotoAssetTypePhoto) {
        PhotoPreviewView *previewView = [self.pageViews objectAtIndex:self.pageControl.currentPage];
        if (!photoAsset.originImage) {
            photoAsset.originImage = previewView.imageView.image;
        }
        if (photoAsset.originImage) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage *filterImage = [PhotoFilter image:photoAsset.originImage withFilter:filterItem.key];
                previewView.imageView.image = filterImage?:photoAsset.originImage;
            });
        }
    }
}
//处理图片
- (void)handleImages{
    for (NSInteger i = 0; i<self.photos.count; i++) {
        PhotoAsset *photoAsset = [self.photos objectAtIndex:i];
        PhotoPreviewView *previewView = [self.pageViews objectAtIndex:i];
        if (previewView.mediaType == PhotoAssetTypeVideo) {
            continue;
        }
        UIImageView *imageView = previewView.imageView;
        photoAsset.originImage = imageView.image;
        if(!photoAsset.originPath || photoAsset.originPath.length == 0){
            NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                UIImage *image = photoAsset.originImage;
                photoAsset.width = image.size.width;
                photoAsset.height = image.size.height;
                NSData *imageData = UIImagePNGRepresentation(image);
                NSString *fn = PHOTO_RANDOM_FILE_NAME(@"png");
                NSString *fp = PHOTO_CACHE_FILE(fn);
                BOOL t = [imageData writeToFile:fp atomically:YES];
                DLOG(@"===fp:%@,%@,file_len:%ld,status:%d", fp,image,imageData.length,t);
                if (t) {
                    photoAsset.originPath = fp;
                }
                //生成缩略图
                photoAsset.thumbImage = [image cropAndScaleToSize:CGSizeMake(200, 200)];
            }];
            [self.photoLoadQueue addOperation:operation];
        }
    }
}
- (void)done:(id)button{
    [BKIndicator showTips:NSLocalizedString(@"handling", @"提示")
                  offsetY: self.view.bounds.size.height - (self.bottomPannel.bounds.size.height+self.view.safeAreaInsets.bottom)
                   inView:self.view
                 duration:-1
               completion:nil
     ];
    [self handleImages];
    dispatch_async(dispatch_get_main_queue(),^{
        [self.photoLoadQueue waitUntilAllOperationsAreFinished];
        
        [BKIndicator tipFadeOutWithDelay:1 completion:^{
            [self dismissViewControllerAnimated:YES completion:^{
                if (self.delegate && [self.delegate respondsToSelector:@selector(photoEditViewController:didEditPhotos:)]) {
                    [self.delegate photoEditViewController:self didEditPhotos:self.photos];
                }
            }];
        }];
    });
}
#pragma UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int currentPage = (scrollView.contentOffset.x+scrollView.bounds.size.width/2)/scrollView.bounds.size.width;
    //    DLOG(@"scrollViewDidScroll, currentPage:%d", currentPage);
    self.pageControl.currentPage = currentPage;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
